<template>
    <div style=" position: relative;"><el-card>
            <template #header>
                <!-- 搜索 -->
                <div>
                    <el-select :disabled="up_btn_data_off" v-model="find_data.userId" clearable placeholder="请选择员工"
                        style="width: 130px;">
                        <el-option v-for="item in upManageOptions" :key="item.ftUserId" :label="item.realName"
                            :value="item.ftUserId">
                            <span style="float: left">{{ item.realName }}</span>
                            <span style="
                            float: right;
                            color: var(--el-text-color-secondary);
                            font-size: 13px;
                          ">{{ item.loginPhone }}</span>
                        </el-option>
                    </el-select>
                    <el-input style="width: 150px;margin-left: 10px;" v-model="find_data.note" placeholder="订单号/订单详情"
                        clearable />
                    <el-select clearable style="width: 100px;margin-left:10px" v-model="find_data.tradeStatus"
                        placeholder="收支情况">
                        <el-option v-for="item in tradeStatus_list" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>

                    <el-date-picker :default-time="defaultTime" style="margin-left: 10px;width: 340px;height:30px"
                        v-model="timeTypeTime" @change="timeTypeTime_btn" type="datetimerange" start-placeholder="开始时间"
                        end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                    <el-select clearable style="width: 150px;margin-left:10px" v-model="find_data.operStatus"
                        placeholder="审核状态">
                        <el-option v-for="item in operStatus_list" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                    <el-select multiple collapse-tags clearable style="width: 150px;margin-left:10px"
                        v-model="find_data.payTypes" placeholder="交易类型">
                        <el-option v-for="item in payType_list" :key="item.id" :label="item.text" :value="item.id" />
                    </el-select>

                    <el-select clearable v-model="find_data.plateNum" :placeholder="'车牌号'"
                        style="width: 150px;margin-left:10px;">
                        <el-option v-for="item in carNumList" :key="item.id" :label="item.plate_num"
                            :value="item.plate_num">
                        </el-option>
                    </el-select>
                    <el-select multiple collapse-tags clearable v-model="companyNums" :placeholder="'托管单位名称'"
                        style="width: 150px;margin-left:10px;">
                        <template #header>
                            <el-checkbox v-model="checkAll" :indeterminate="indeterminate" @change="handleCheckAll">
                                全选
                            </el-checkbox>
                        </template>
                        <el-option v-for="item in findTrusteeshipMeComboList" :key="item.id" :label="item.companyName"
                            :value="item.companyNum">
                        </el-option>
                    </el-select>

                    <el-button style="margin-left: 20px;height:30px" @click="search_btn" type="primary"
                        icon="Search">搜索</el-button>
                </div>
                <!-- 功能按钮 -->
                <div style="margin-top:10px;display: flex;">
                    <el-tag type="danger" style="margin-left: 10px;font-weight: 700;height:25px;line-height:25px">总金额：{{
                        sumTradeMoney
                    }}</el-tag>
                    <el-tag type="success"
                        style="margin-left: 10px;font-weight: 700;height:25px;line-height:25px">已操作：{{
                            payMoney
                        }}</el-tag>
                    <el-tag type="warning"
                        style="margin-left: 10px;font-weight: 700;height:25px;line-height:25px">未操作：{{
                            gathMoney
                        }}</el-tag>
                    <el-button style="margin-left: 10px" @click="createStaffReim_btn" type="primary"
                        icon="SuccessFilled">生成员工报账</el-button>
                    <!-- <el-button @click="up_btn" type="warning" icon="WarnTriangleFilled">修改</el-button>
                    <el-button @click="del_btn" type="danger" icon="CircleCloseFilled">删除</el-button> -->
                </div>
            </template>
            <div>
                <el-table border @header-dragend='headerdragend' @selection-change="selection_change_btn" height="67vh"
                    ref="multipleTableRef" :data="list_data" style="width: 100%">
                    <el-table-column type="selection" width="35" />
                    <el-table-column label="编号" width="55" fixed type="index" />
                    <template v-for="item in table_data_list_new" :key="item.field">
                        <el-table-column v-if="item.off" :width="item.width" :prop="item.field" :label="item.label">
                            <template v-if="item.field == 'balType'" #="{ row, column, $index }">
                                {{ row.balType == 'SALARY_BALANCE' ? '工资余额' : '无' }}
                            </template>
                            <template v-if="item.field == 'payType'" #="{ row, column, $index }">
                                {{ row.payType == 'SALARY' ? '佣金收入' : row.payType == 'PUNISH_MONEY' ? '订单处罚金额' :
                                    row.payType
                                        == 'INDEMNIFY_MONEY' ? '赔偿金额' : row.payType == 'SAFETY_MONEY' ? '安全奖励' : row.payType ==
                                            'PRAISE_MONEY' ? '表扬奖励' : row.payType == 'GRIEVANCE_MONEY' ? '委屈奖励' : row.payType ==
                                                'NO_PUNISH_MONEY' ? '无投诉奖励' : row.payType == 'DRAW_SALARY' ? '佣金提现' : '' }}
                            </template>
                            <template v-if="item.field == 'operMark2'" #="{ row, column, $index }">
                                {{ row.operMark ? '已核销' : row.staffReimburseId ? '已生成员工报账' : '未操作' }}

                            </template>
                            <template v-if="item.field == 'tradeStatus'" #="{ row, column, $index }">
                                {{ row.tradeStatus == 'INCOME' ? '收入' : '支出' }}
                            </template>
                        </el-table-column>
                    </template>


                </el-table>
            </div>

            <div style="margin-top:20px">
                <el-pagination @current-change="current_change_btn" @size-change="size_change_btn"
                    v-model:current-page="find_data.page.pageNum" v-model:page-size="find_data.page.pageSize"
                    :page-sizes="[100, 200, 300, 500]" :background="true"
                    layout="prev, pager, next, jumper,->,sizes,total," :total="total" />
            </div>
        </el-card>
    </div>

    <!-- 弹窗 -->
    <div>
        <!-- 表格筛选 -->
        <div style="position: absolute;top:100px;z-index: 9999;" :style="icon_off ? 'right:0px;' : 'right:110px;'">
            <el-icon @click="icon_btn" :size="20">
                <Setting />
            </el-icon>
            <div v-show="icon_off"
                style=" position: relative;top:-100px;right:140px;width: 130px;height:430px;background:#fff;overflow: hidden;">
                <div class="cols-set" style="background:#fff;width:90%;height:97%;margin:auto;margin-top:10px;">
                    <div>
                        <el-button-group style="display: flex; ">
                            <el-tooltip effect="dark" placement="bottom">
                                <template #content>注意：拖动下面的项，可以改变表格列的顺序，<br />记得点击保存才会永久生效哦！ </template>
                                <el-button style="width:10px" type="primary" icon="WarningFilled"></el-button>
                            </el-tooltip>
                            <el-button title="重置" type="primary" icon="Refresh" @click="resetTableSet"></el-button>
                            <el-button title="保存" type="primary" icon="Check" @click="saveTableSet"></el-button>
                        </el-button-group>
                        <div ref="sortableContainer" class="col-items" style="height:400px; overflow-y: auto; ">
                            <el-checkbox class="drag_it" @change="checkbox_btn" v-for="item in sortedItems"
                                :key="item.field" v-model="item.off" :label="item.label" border>
                            </el-checkbox>
                        </div>

                    </div>
                </div>
            </div>
        </div>
        <!-- 添加修改 -->
        <el-dialog style="margin-top:5vh" v-model="add_off" :title="title" width="40%" :close-on-click-modal='false'>
            <el-form :model="add_data" ref="formRef" label-width="130px" label-suffix="：">
                <el-form-item label="账户名称" prop="bankName" :rules="[
                    { required: true, message: '请输入账户名称', trigger: 'blur' },
                ]">
                    <el-input style="width: 400px;" maxlength="30" show-word-limit clearable v-model="add_data.bankName"
                        placeholder="请输入账户名称" />
                </el-form-item>
                <el-form-item prop="cardName" label="开户行" :rules="[
                    { required: true, message: '请输入开户行', trigger: 'blur' },
                ]">
                    <el-input maxlength="30" show-word-limit clearable style="width: 400px;" v-model="add_data.cardName"
                        placeholder="请输入开户行" />
                </el-form-item>
                <el-form-item label="账号" prop="cardNo" :rules="[{ required: true, message: '请输入账号', trigger: 'blur' }]">
                    <el-input maxlength="30" show-word-limit clearable style="width: 400px;" v-model="add_data.cardNo"
                        placeholder="请输入账户名称" />
                </el-form-item>
            </el-form>


            <el-button @click="ok_btn" style="margin-left:30vw" type="primary">确认提交</el-button>
        </el-dialog>
    </div>
</template>

<script setup>
import Sortable from 'sortablejs';
import { GET_TOKEN } from '@/utils/token.js'
import { ref, reactive, onMounted, computed, watch } from 'vue'
import {
    adupPrivateSet, getPrivateSetList, getWalletListForCompany, findStaffCombo, getBalanceTypes, getTradeTypes,
    createStaffReim, findCarCombo, findTrusteeshipMeCombo
} from '@/api/financial_center.js'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import { importCusCheckInData } from '@/utils/common.js'
import CircularJSON from 'circular-json'
onMounted(async () => {

    // getBalanceTypes({}).then(res => {

    // })


    getPrivateSetList({
        find: '工资明细',
        page: {
            pageNum: 1,
            pageSize: 20,
        },
    }).then(res => {
        if (res.data.list[0]) {
            table_data_list_new.value = JSON.parse(res.data.list[res.data.list.length - 1].dat)
        } else {
            console.log('no')
            table_data_list_new.value = table_data_list
        }
    })


    findTrusteeshipMeCombo({
        page: {
            pageNum: 1,
            pageSize: 999,
        },
        companyName: '',
    }).then(res => {
        let luser = JSON.parse(localStorage.getItem("luser"))
        let luser_companyNum = luser.companyNum
        let companyNums = [luser_companyNum]
        if (res.data) {
            for (let i = 0; i < res.data.length; i++) {
                console.log(res.data[i].companyNum)
                companyNums.push(res.data[i].companyNum)
            }
        }
        findCarCombo({
            page: {
                pageNum: 1,
                pageSize: 999,
            },
            plateNum: '',
            companyNums: companyNums,
        }).then(res => {

            carNumList.value = res.data.list || [];
        })
    })

    Sortable.create(sortableContainer.value, {
        draggable: '.drag_it',
        ghostClass: 'sortable-ghost',
        onEnd: evt => {
            const targetRow = table_data_list_new.value.splice(evt.oldIndex, 1)[0];
            table_data_list_new.value.splice(evt.newIndex, 0, targetRow);
        }
    })


    findStaffCombo({}).then(res => {
        upManageOptions.value = res.data
    })
    getTradeTypes({}).then(res => {
        payType_list.value = res.data
    })
    findTrusteeshipMeCombo({
        page: {
            pageNum: 1,
            pageSize: 999,
        },
        companyName: '',
    }).then(res => {
        findTrusteeshipMeComboList.value = res.data || [];
    })
    timeTypeTime.value = [new_day(), to_day()]
    find_data.stime = new_day()
    find_data.etime = to_day()
    setTimeout(() => {
        for (let i = 0; i < findTrusteeshipMeComboList.value.length; i++) {
            companyNums.value.push(findTrusteeshipMeComboList.value[i].companyNum)
        }
        checkAll.value = true

        list_api()
    }, 500);

    company.value = JSON.parse(localStorage.getItem("company"))
    isTrustee.value = company.value.isTrustee

})

const checkAll = ref(false)
const indeterminate = ref(false)
const findTrusteeshipMeComboList = ref([])
const companyNums = ref([])
watch(companyNums, (val) => {

    if (val.length === 0) {
        checkAll.value = false
        indeterminate.value = false
    } else if (val.length === findTrusteeshipMeComboList.value.length) {
        checkAll.value = true
        indeterminate.value = false
    } else {
        indeterminate.value = true
    }
})
const handleCheckAll = (val) => {
    indeterminate.value = false
    if (val) {
        companyNums.value = findTrusteeshipMeComboList.value.map((_) => _.companyNum)
    } else {
        companyNums.value = []
    }

}

//#region 是否托管
const company = ref({})
const isTrustee = ref(0)
//#endregion
const carNumList = ref([])
const upManageOptions = ref([])
const tradeStatus_list = reactive([{
    value: 'INCOME',
    label: '收入',
},
{
    value: 'PAY',
    label: '支出',
},])
const new_day = () => {
    // 获取当前日期
    let currentDate = new Date();

    // 计算上个月的年份和月份
    let year = currentDate.getMonth() === 0 ? currentDate.getFullYear() - 1 : currentDate.getFullYear();
    let month = currentDate.getMonth() === 0 ? 11 : currentDate.getMonth() - 1;

    // 构建上个月的日期
    let firstDayOfLastMonth = new Date(year, month, 1);

    // 格式化为 yyyy-mm-dd
    let formattedDate = `${firstDayOfLastMonth.getFullYear()}-${(firstDayOfLastMonth.getMonth() + 1).toString().padStart(2, '0')}-01`;

    let formattedDate2 = `${formattedDate} 00:00:00`;
    return formattedDate2
}
const to_day = () => {
    // 获取当前日期
    let currentDate = new Date();

    // 计算上个月的年份和月份
    let year = currentDate.getMonth() === 0 ? currentDate.getFullYear() - 1 : currentDate.getFullYear();
    let month = currentDate.getMonth() === 0 ? 11 : currentDate.getMonth() - 1;

    // 获取上个月的最后一天
    let lastDayOfLastMonth = new Date(year, month + 1, 0);

    // 格式化为 yyyy-mm-dd
    let formattedDate = `${lastDayOfLastMonth.getFullYear()}-${(lastDayOfLastMonth.getMonth() + 1).toString().padStart(2, '0')}-${lastDayOfLastMonth.getDate()}`;

    let formattedDate2 = `${formattedDate} 23:59:59`;
    return formattedDate2
}
const timeTypeTime = ref('')
const timeTypeTime_btn = (e) => {
    if (e) {
        timeTypeTime.value = e
        find_data.stime = timeTypeTime.value[0]
        find_data.etime = timeTypeTime.value[1]
    } else {
        timeTypeTime.value = ''
        find_data.stime = ''
        find_data.etime = ''
    }
}
const operStatus_list = reactive([{
    value: 'UNOPER',
    label: '未操作',
},
{
    value: 'YSCYGBZ',
    label: '已生成员工报账',
},])
//#region 表格数据处理
const table_data_list = reactive([
    { label: '订单号', field: 'orderNum', width: 180, off: true },
    { label: '驾驶员', field: 'realName', width: 120, off: true },
    { label: '账户类型', field: 'balType', width: 100, off: true },
    { label: '收入状态', field: 'tradeStatus', width: 100, off: true },
    { label: '金额', field: 'amoney', width: 100, off: true },
    { label: '交易后余额', field: 'cashBalance', width: 100, off: true },
    { label: '行程备注', field: 'note', width: 400, off: true },
    { label: '车牌号', field: 'plateNum', width: 120, off: true },
    { label: '交易类型', field: 'payType', width: 100, off: true },
    { label: '状态', field: 'operMark2', width: 100, off: true },
    { label: '操作备注', field: 'assist', width: 220, off: true },
    { label: '操作编号', field: 'operMark', width: 180, off: true },
    { label: '添加时间', field: 'addTime', width: 170, off: true },

])

const table_data_list_new = ref([])
const icon_off = ref(false)
// 创建排序容器的引用
const sortableContainer = ref('')

const icon_btn = () => {
    icon_off.value = !icon_off.value
    console.log(sortableContainer.value)

}
const resetTableSet = () => {
    console.log(table_data_list)
    table_data_list_new.value = JSON.parse(JSON.stringify(table_data_list))
    console.log(table_data_list)
    console.log(table_data_list_new.value)
}
const saveTableSet = () => {
    adupPrivateSet({
        dat: JSON.stringify(table_data_list_new.value),
        tbName: '工资明细',
        tbNum: "salary_details",
    }).then(res => {
        if (res.code == 1) {
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
    icon_off.value = false
}

const checkbox_btn = (e, c) => {
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (table_data_list_new.value[i].label == c.target._value) {
            table_data_list_new.value[i].off == e

        }

    }

}

const sortedItems = computed(() => {
    return [...table_data_list_new.value].sort((a, b) => a.id - b.id);
})
//#endregion



//#region 分页列表
const payType_list = ref([])
const list_data = ref([])
const find_data = reactive({
    page: {
        pageNum: 1,
        pageSize: 200,
    },
    payTypes: ['SALARY', 'PUNISH_MONEY', 'INDEMNIFY_MONEY', 'PRAISE_MONEY', 'GRIEVANCE_MONEY'],
    balType: 'SALARY_BALANCE',
    stime: "",
    etime: "",
    note: "",
    operStatus: "",
    tradeStatus: "",
    userId: "",
    plateNum: '',
    companyNums: [],

})
const total = ref(0)

// 分页器一夜显示多少数据页面
const size_change_btn = () => {
    find_data.page.pageNum = 1
    list_api()
}

// 分页器跳转页面
const current_change_btn = () => {
    list_api()
}
const gathMoney = ref(0)
const payMoney = ref(0)
const sumTradeMoney = ref(0)
const list_api = () => {
    find_data.companyNums = companyNums.value
    getWalletListForCompany(find_data).then(res => {
        list_data.value = res.data.list.list
        total.value = res.data.list.total
        gathMoney.value = res.data.statics.notOperMoney
        payMoney.value = res.data.statics.operMoney
        sumTradeMoney.value = res.data.statics.totalMoney

    })
}
//#endregion
const defaultTime = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]

//#region 添加
const add_off = ref(false)
const title = ref('添加账户')
const add_data = reactive({
    bankName: "",
    cardName: "",
    cardNo: "",
    id: "",
})
const add_btn = () => {
    title.value = '添加账户'

    add_data.bankName = ''
    add_data.cardName = ''
    add_data.cardNo = ''
    add_data.id = ''
    add_off.value = true

}


//#endregion

//#region 表格选择
const table_list = ref([])
const headerdragend = (newWidth, oldWidth, column) => {
    console.log(newWidth, oldWidth, column)
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (column.property == table_data_list_new.value[i].field) {
            table_data_list_new.value[i].width = newWidth
        }
    }
}
const selection_change_btn = (e) => {
    table_list.value = e
    console.log(e)
}
//#endregion
//#region 修改
const up_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }


    title.value = '修改账户'
    add_data.bankName = table_list.value[0].bankName
    add_data.cardName = table_list.value[0].cardName
    add_data.cardNo = table_list.value[0].cardNo
    add_data.id = table_list.value[0].id
    add_off.value = true
}
//#endregion

// 提交
const ok_btn = () => {

    if (!add_data.bankName) {
        return ElMessage({
            message: '请输入账户名称',
            type: 'warning',
        })
    } else if (!add_data.cardName) {
        return ElMessage({
            message: '请输入开户行',
            type: 'warning',
        })
    } else if (!add_data.cardNo) {
        return ElMessage({
            message: '请输入卡号',
            type: 'warning',
        })
    }
    if (title.value == '添加账户') {

        adupBank(add_data).then(res => {
            if (res.code == 1) {
                list_api()
                add_off.value = false
                return ElMessage({
                    message: res.msg,
                    type: 'success',
                })
            } else {
                return ElMessage({
                    message: res.msg,
                    type: 'warning',
                })
            }
        })
    } else {

        adupBank(add_data).then(res => {
            if (res.code == 1) {
                list_api()
                add_off.value = false
                return ElMessage({
                    message: res.msg,
                    type: 'success',
                })
            } else {
                return ElMessage({
                    message: res.msg,
                    type: 'warning',
                })
            }
        })
    }
}


//#region 生成员工报账
const createStaffReim_btn = () => {
    if (table_list.value.length < 1) {
        return ElMessage({
            message: '请选择至少一条数据！',
            type: 'warning',
        })
    }

    let no_off = 1
    let luser = JSON.parse(localStorage.getItem("luser"))
    let luser_companyNum = luser.companyNum
    let arrcompanyNum = []
    for (let i = 0; i < table_list.value.length; i++) {
        if (table_list.value[i].driverBelongCompanyInfo) {
            let data = table_list.value[i].driverBelongCompanyInfo
            let parts = data.split('-')[0]
            if (parts != luser_companyNum) {
                no_off = 0
            }
        } else {
            no_off = 1
        }

    }
    if (no_off == 0) {
        ElMessageBox.confirm(
            `此员工不是该单位的员工无法生产员工报账！`,
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                showCancelButton: false,
                type: 'warning',
                distinguishCancelAndClose: 'true',
            }
        )
            .then(() => {

            })
            .catch((e) => {


            })
    } else {
        ElMessageBox.confirm(
            `是否生成员工报账?`,
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                distinguishCancelAndClose: 'true',
            }
        )
            .then(() => {
                const loading = ElLoading.service({
                    lock: true,
                    text: '生成中...',
                    background: 'rgba(0, 0, 0, 0.7)',
                })
                let ids = []
                for (let i = 0; i < table_list.value.length; i++) {
                    ids.push(table_list.value[i].id)
                }
                createStaffReim({
                    ids: ids
                }).then(res => {
                    if (res.code == 1) {
                        list_api()
                        loading.close()
                        return ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                    } else {
                        loading.close()
                        return ElMessage({
                            message: res.msg,
                            type: 'warning',
                        })
                    }
                })
            })
            .catch((e) => {


            })
    }






}
//#endregion

//#region 搜索
const search_btn = () => {
    list_api()
}
//#endregion


</script>

<style scoped lang='scss'></style>

<style>
.col-items::-webkit-scrollbar {
    width: 5px !important;
}

.col-items>label {
    margin-left: 0px !important;
    margin-top: 5px;
    width: 100%;
}


.el-table .el-table__cell {
    padding: 0px !important;
}
</style>
